<template>
  <div id="mapView" class="map-view">
    <!-- 图层控制面板 -->
    <div class="layer-control-panel">
      <el-card class="layer-card">
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="图层显示控制" name="layers">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-checkbox
                v-model="layerVisibility.entrance"
                @change="toggleLayerVisibility('entrance')"
                >进出口</el-checkbox
              >
              <el-checkbox
                v-model="layerVisibility.service"
                @change="toggleLayerVisibility('service')"
                >服务区</el-checkbox
              >
            </el-space>
          </el-collapse-item>
          <el-collapse-item title="图层操作控制" name="operations">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-button type="primary" @click="startAddEntrance" :disabled="isDrawing">
                <el-icon><Plus /></el-icon> 新增进出口
              </el-button>
              <el-button type="primary" @click="startAddService" :disabled="isDrawing">
                <el-icon><Plus /></el-icon> 新增服务区
              </el-button>
            </el-space>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>

    <!-- 进出口属性表单对话框 -->
    <el-dialog
      v-model="entranceFormVisible"
      :title="formMode === 'add' ? '新增进出口' : '编辑进出口'"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="entranceForm"
        label-width="120px"
        :rules="entranceFormRules"
        ref="entranceFormRef"
      >
        <el-form-item label="进出口编号" prop="entrance_id">
          <el-input v-model="entranceForm.entrance_id" placeholder="请输入进出口编号"></el-input>
        </el-form-item>
        <el-form-item label="进出口名称" prop="entrance_name">
          <el-input v-model="entranceForm.entrance_name" placeholder="请输入进出口名称"></el-input>
        </el-form-item>
        <el-form-item label="进出口类型" prop="entrance_type">
          <el-select
            v-model="entranceForm.entrance_type"
            placeholder="请选择进出口类型"
            style="width: 100%"
          >
            <el-option label="入口" value="入口"></el-option>
            <el-option label="出口" value="出口"></el-option>
            <el-option label="出入口" value="出入口"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属高速公路" prop="highway_code">
          <el-select
            v-model="entranceForm.highway_code"
            placeholder="请选择所属高速公路"
            style="width: 100%"
          >
            <el-option
              v-for="highway in highwayList"
              :key="highway.attributes.OBJECTID"
              :label="highway.attributes.highway_name"
              :value="highway.attributes.highway_code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收费站状态" prop="status">
          <el-select
            v-model="entranceForm.status"
            placeholder="请选择收费站状态"
            style="width: 100%"
          >
            <el-option label="正常" value="正常"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
            <el-option label="关闭" value="关闭"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="位置描述" prop="location_desc">
          <el-input
            v-model="entranceForm.location_desc"
            type="textarea"
            placeholder="请输入位置描述"
            :rows="2"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEntranceForm">取消</el-button>
          <el-button type="primary" @click="submitEntranceForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 进出口属性查看对话框 -->
    <el-dialog
      v-model="entranceInfoVisible"
      title="进出口信息"
      width="500px"
      :key="refreshEntranceKey"
    >
      <div v-if="selectedEntrance">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="进出口编号">{{
            selectedEntrance.attributes.entrance_id
          }}</el-descriptions-item>
          <el-descriptions-item label="进出口名称">{{
            selectedEntrance.attributes.entrance_name
          }}</el-descriptions-item>
          <el-descriptions-item label="进出口类型">{{
            selectedEntrance.attributes.entrance_type
          }}</el-descriptions-item>
          <el-descriptions-item label="所属高速公路">{{
            getHighwayNameByCode(selectedEntrance.attributes.highway_code)
          }}</el-descriptions-item>
          <el-descriptions-item label="收费站状态">{{
            selectedEntrance.attributes.status
          }}</el-descriptions-item>
          <el-descriptions-item label="位置描述">{{
            selectedEntrance.attributes.location_desc
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="entranceInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="editEntrance">编辑</el-button>
          <el-button type="danger" @click="confirmDeleteEntrance">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 服务区属性表单对话框 -->
    <el-dialog
      v-model="serviceFormVisible"
      :title="formMode === 'add' ? '新增服务区' : '编辑服务区'"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="serviceForm"
        label-width="120px"
        :rules="serviceFormRules"
        ref="serviceFormRef"
      >
        <el-form-item label="服务区编号" prop="service_id">
          <el-input v-model="serviceForm.service_id" placeholder="请输入服务区编号"></el-input>
        </el-form-item>
        <el-form-item label="服务区名称" prop="service_name">
          <el-input v-model="serviceForm.service_name" placeholder="请输入服务区名称"></el-input>
        </el-form-item>
        <el-form-item label="所属高速公路" prop="highway_code">
          <el-select
            v-model="serviceForm.highway_code"
            placeholder="请选择所属高速公路"
            style="width: 100%"
          >
            <el-option
              v-for="highway in highwayList"
              :key="highway.attributes.OBJECTID"
              :label="highway.attributes.highway_name"
              :value="highway.attributes.highway_code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务区等级" prop="service_level">
          <el-select
            v-model="serviceForm.service_level"
            placeholder="请选择服务区等级"
            style="width: 100%"
          >
            <el-option label="一星级" value="一星级"></el-option>
            <el-option label="二星级" value="二星级"></el-option>
            <el-option label="三星级" value="三星级"></el-option>
            <el-option label="四星级" value="四星级"></el-option>
            <el-option label="五星级" value="五星级"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务区状态" prop="status">
          <el-select
            v-model="serviceForm.status"
            placeholder="请选择服务区状态"
            style="width: 100%"
          >
            <el-option label="正常" value="正常"></el-option>
            <el-option label="维修中" value="维修中"></el-option>
            <el-option label="关闭" value="关闭"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设施描述" prop="facilities">
          <el-input
            v-model="serviceForm.facilities"
            type="textarea"
            placeholder="请输入设施描述"
            :rows="2"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelServiceForm">取消</el-button>
          <el-button type="primary" @click="submitServiceForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 服务区属性查看对话框 -->
    <el-dialog
      v-model="serviceInfoVisible"
      title="服务区信息"
      width="500px"
      :key="refreshServiceKey"
    >
      <div v-if="selectedService">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="服务区编号">{{
            selectedService.attributes.service_id
          }}</el-descriptions-item>
          <el-descriptions-item label="服务区名称">{{
            selectedService.attributes.service_name
          }}</el-descriptions-item>
          <el-descriptions-item label="所属高速公路">{{
            getHighwayNameByCode(selectedService.attributes.highway_code)
          }}</el-descriptions-item>
          <el-descriptions-item label="服务区等级">{{
            selectedService.attributes.service_level
          }}</el-descriptions-item>
          <el-descriptions-item label="服务区状态">{{
            selectedService.attributes.status
          }}</el-descriptions-item>
          <el-descriptions-item label="设施描述">{{
            selectedService.attributes.facilities
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="serviceInfoVisible = false">关闭</el-button>
          <el-button type="primary" @click="editService">编辑</el-button>
          <el-button type="danger" @click="confirmDeleteService">删除</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteConfirmVisible" title="确认删除" width="300px">
      <p>{{ deleteConfirmMessage }}</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteConfirmVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, reactive, nextTick } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel.js'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol.js'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol.js'
import Query from '@arcgis/core/rest/support/Query.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'

type EntranceFormType = {
  entrance_id: string
  entrance_name: string
  entrance_type: string
  highway_code: string
  status: string
  location_desc: string
}

type ServiceFormType = {
  service_id: string
  service_name: string
  highway_code: string
  service_level: string
  status: string
  facilities: string
}

let view: MapView | null = null
let entranceLayer: FeatureLayer | null = null
let serviceLayer: FeatureLayer | null = null
let highwayLayer: FeatureLayer | null = null
let sketchLayer: GraphicsLayer | null = null
let sketchViewModel: SketchViewModel | null = null
let tempGraphic: Graphic | null = null

// 图层可见性控制
const layerVisibility = ref({
  entrance: true,
  service: true,
}) as any

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'operations'])
// 添加刷新标记
const refreshEntranceKey = ref(0)
const refreshServiceKey = ref(0)

// 表单相关
const entranceFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const entranceFormVisible = ref(false)
const formMode = ref<'add' | 'edit'>('add')
const isDrawing = ref(false)
const entranceInfoVisible = ref(false)
const deleteConfirmVisible = ref(false)
let selectedEntrance: Graphic | null = null

// 服务区表单相关
const serviceFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const serviceFormVisible = ref(false)
const serviceInfoVisible = ref(false)
let selectedService: Graphic | null = null

// 删除确认相关
const deleteConfirmMessage = ref('')
const deleteType = ref<'entrance' | 'service'>('entrance')
const isPoint = ref(false)
// 将响应式变量改回普通变量
let highwayList: Graphic[] = []

// 进出口表单数据
const entranceForm = reactive<EntranceFormType>({
  entrance_id: '',
  entrance_name: '',
  entrance_type: '出入口',
  highway_code: '',
  status: '正常',
  location_desc: '',
})

// 服务区表单数据
const serviceForm = reactive<ServiceFormType>({
  service_id: '',
  service_name: '',
  highway_code: '',
  service_level: '三星级',
  status: '正常',
  facilities: '',
})

// 进出口表单验证规则
const entranceFormRules = {
  entrance_id: [{ required: true, message: '请输入进出口编号', trigger: 'blur' }],
  entrance_name: [{ required: true, message: '请输入进出口名称', trigger: 'blur' }],
  entrance_type: [{ required: true, message: '请选择进出口类型', trigger: 'change' }],
  highway_code: [{ required: true, message: '请选择所属高速公路', trigger: 'change' }],
  status: [{ required: true, message: '请选择收费站状态', trigger: 'change' }],
  location_desc: [{ required: true, message: '请输入位置描述', trigger: 'blur' }],
}

// 服务区表单验证规则
const serviceFormRules = {
  service_id: [{ required: true, message: '请输入服务区编号', trigger: 'blur' }],
  service_name: [{ required: true, message: '请输入服务区名称', trigger: 'blur' }],
  highway_code: [{ required: true, message: '请选择所属高速公路', trigger: 'change' }],
  service_level: [{ required: true, message: '请选择服务区等级', trigger: 'change' }],
  status: [{ required: true, message: '请选择服务区状态', trigger: 'change' }],
  facilities: [{ required: true, message: '请输入设施描述', trigger: 'blur' }],
}

// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  if (layerType === 'entrance' && entranceLayer) {
    entranceLayer.visible = Boolean(layerVisibility.value.entrance)
  } else if (layerType === 'service' && serviceLayer) {
    serviceLayer.visible = Boolean(layerVisibility.value.service)
  }
}

// 开始添加进出口
const startAddEntrance = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上点击添加进出口位置')
  isPoint.value = true
  // 开始绘制点
  sketchViewModel.create('point')
}

// 开始添加服务区
const startAddService = () => {
  if (!view || !sketchViewModel) return

  isDrawing.value = true
  ElMessage.info('请在地图上点击添加服务区位置')
  isPoint.value = false
  // 开始绘制点
  sketchViewModel.create('polygon')
}

// 取消进出口表单
const cancelEntranceForm = () => {
  entranceFormVisible.value = false
  resetEntranceForm()

  // 如果是添加模式，清除临时图形
  if (formMode.value === 'add' && tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }

  isDrawing.value = false
}

// 取消服务区表单
const cancelServiceForm = () => {
  serviceFormVisible.value = false
  resetServiceForm()

  // 如果是添加模式，清除临时图形
  if (formMode.value === 'add' && tempGraphic && sketchLayer) {
    sketchLayer.remove(tempGraphic)
    tempGraphic = null
  }

  isDrawing.value = false
}

// 重置进出口表单
const resetEntranceForm = () => {
  if (entranceFormRef.value) {
    entranceFormRef.value.resetFields()
  }

  entranceForm.entrance_id = ''
  entranceForm.entrance_name = ''
  entranceForm.entrance_type = '出入口'
  entranceForm.highway_code = ''
  entranceForm.status = '正常'
  entranceForm.location_desc = ''
}

// 重置服务区表单
const resetServiceForm = () => {
  if (serviceFormRef.value) {
    serviceFormRef.value.resetFields()
  }

  serviceForm.service_id = ''
  serviceForm.service_name = ''
  serviceForm.highway_code = ''
  serviceForm.service_level = '三星级'
  serviceForm.status = '正常'
  serviceForm.facilities = ''
}

// 提交进出口表单
const submitEntranceForm = async () => {
  if (!entranceFormRef.value) return

  await entranceFormRef.value.validate(async (valid) => {
    if (valid) {
      if (formMode.value === 'add') {
        // 添加新进出口
        addEntrance()
      } else {
        // 更新进出口
        updateEntrance()
      }
    }
  })
}

// 提交服务区表单
const submitServiceForm = async () => {
  if (!serviceFormRef.value) return

  await serviceFormRef.value.validate(async (valid) => {
    if (valid) {
      if (formMode.value === 'add') {
        // 添加新服务区
        addService()
      } else {
        // 更新服务区
        updateService()
      }
    }
  })
}

// 添加新进出口
const addEntrance = () => {
  if (!tempGraphic || !entranceLayer) return

  // 创建新的进出口图形
  const attributes = {
    entrance_id: entranceForm.entrance_id,
    entrance_name: entranceForm.entrance_name,
    entrance_type: entranceForm.entrance_type,
    highway_code: entranceForm.highway_code,
    status: entranceForm.status,
    location_desc: entranceForm.location_desc,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })

  // 添加到图层
  entranceLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      if (result.addFeatureResults.length > 0) {
        ElMessage.success('进出口添加成功')
        entranceFormVisible.value = false
        resetEntranceForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.remove(tempGraphic)
          tempGraphic = null
        }

        isDrawing.value = false
      } else {
        ElMessage.error('进出口添加失败')
      }
    })
    .catch((error) => {
      console.error('添加进出口出错:', error)
      ElMessage.error('进出口添加失败')
    })
}

// 添加新服务区
const addService = () => {
  if (!tempGraphic || !serviceLayer) return

  // 创建新的服务区图形
  const attributes = {
    service_id: serviceForm.service_id,
    service_name: serviceForm.service_name,
    highway_code: serviceForm.highway_code,
    service_level: serviceForm.service_level,
    status: serviceForm.status,
    facilities: serviceForm.facilities,
  }

  // 创建新的图形
  const newGraphic = new Graphic({
    geometry: tempGraphic.geometry,
    attributes: attributes,
  })

  // 添加到图层
  serviceLayer
    .applyEdits({
      addFeatures: [newGraphic],
    })
    .then((result) => {
      if (result.addFeatureResults.length > 0) {
        ElMessage.success('服务区添加成功')
        serviceFormVisible.value = false
        resetServiceForm()

        // 清除临时图形
        if (sketchLayer && tempGraphic) {
          sketchLayer.remove(tempGraphic)
          tempGraphic = null
        }

        isDrawing.value = false
      } else {
        ElMessage.error('服务区添加失败')
      }
    })
    .catch((error) => {
      console.error('添加服务区出错:', error)
      ElMessage.error('服务区添加失败')
    })
}

// 编辑进出口
const editEntrance = () => {
  if (!selectedEntrance) return

  formMode.value = 'edit'

  // 填充表单数据
  const attrs = selectedEntrance.attributes
  entranceForm.entrance_id = attrs.entrance_id || ''
  entranceForm.entrance_name = attrs.entrance_name || ''
  entranceForm.entrance_type = attrs.entrance_type || '出入口'
  entranceForm.highway_code = attrs.highway_code || ''
  entranceForm.status = attrs.status || '正常'
  entranceForm.location_desc = attrs.location_desc || ''

  entranceInfoVisible.value = false
  entranceFormVisible.value = true
}

// 编辑服务区
const editService = () => {
  if (!selectedService) return

  formMode.value = 'edit'

  // 填充表单数据
  const attrs = selectedService.attributes
  serviceForm.service_id = attrs.service_id || ''
  serviceForm.service_name = attrs.service_name || ''
  serviceForm.highway_code = attrs.highway_code || ''
  serviceForm.service_level = attrs.service_level || '三星级'
  serviceForm.status = attrs.status || '正常'
  serviceForm.facilities = attrs.facilities || ''

  serviceInfoVisible.value = false
  serviceFormVisible.value = true
}

// 更新进出口
const updateEntrance = () => {
  if (!selectedEntrance || !entranceLayer) return

  // 更新属性
  const updatedGraphic = selectedEntrance.clone()
  updatedGraphic.attributes.entrance_id = entranceForm.entrance_id
  updatedGraphic.attributes.entrance_name = entranceForm.entrance_name
  updatedGraphic.attributes.entrance_type = entranceForm.entrance_type
  updatedGraphic.attributes.highway_code = entranceForm.highway_code
  updatedGraphic.attributes.status = entranceForm.status
  updatedGraphic.attributes.location_desc = entranceForm.location_desc

  // 提交更新到服务
  entranceLayer
    .applyEdits({
      updateFeatures: [updatedGraphic],
    })
    .then((result) => {
      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('进出口更新成功')
        entranceFormVisible.value = false
        resetEntranceForm()
        refreshEntranceKey.value += 1
      } else {
        ElMessage.error('进出口更新失败')
      }
    })
    .catch((error) => {
      console.error('更新进出口出错:', error)
      ElMessage.error('进出口更新失败')
    })
}

// 更新服务区
const updateService = () => {
  if (!selectedService || !serviceLayer) return

  // 更新属性
  const updatedGraphic = selectedService.clone()
  updatedGraphic.attributes.service_id = serviceForm.service_id
  updatedGraphic.attributes.service_name = serviceForm.service_name
  updatedGraphic.attributes.highway_code = serviceForm.highway_code
  updatedGraphic.attributes.service_level = serviceForm.service_level
  updatedGraphic.attributes.status = serviceForm.status
  updatedGraphic.attributes.facilities = serviceForm.facilities

  // 提交更新到服务
  serviceLayer
    .applyEdits({
      updateFeatures: [updatedGraphic],
    })
    .then((result) => {
      if (result.updateFeatureResults.length > 0) {
        ElMessage.success('服务区更新成功')
        serviceFormVisible.value = false
        resetServiceForm()
        refreshServiceKey.value += 1
      } else {
        ElMessage.error('服务区更新失败')
      }
    })
    .catch((error) => {
      console.error('更新服务区出错:', error)
      ElMessage.error('服务区更新失败')
    })
}

// 根据高速公路编号获取名称
const getHighwayNameByCode = (code: string) => {
  const highway = highwayList.find((h) => h.attributes.highway_code === code)
  return highway ? highway.attributes.highway_name : '未知'
}

// 加载高速公路列表
const loadHighwayList = () => {
  if (!highwayLayer) return

  const query = new Query()
  query.where = '1=1' // 查询所有高速公路
  query.outFields = ['*']
  query.returnGeometry = false

  highwayLayer
    .queryFeatures(query)
    .then((results) => {
      highwayList = results.features
    })
    .catch((error) => {
      console.error('加载高速公路列表出错:', error)
      ElMessage.error('加载高速公路列表失败')
    })
}

// 确认删除进出口
const confirmDeleteEntrance = () => {
  if (!selectedEntrance) return

  deleteType.value = 'entrance'
  deleteConfirmMessage.value = `确定要删除进出口 "${selectedEntrance.attributes.entrance_name}" 吗？此操作不可恢复。`
  deleteConfirmVisible.value = true
}

// 确认删除服务区
const confirmDeleteService = () => {
  if (!selectedService) return

  deleteType.value = 'service'
  deleteConfirmMessage.value = `确定要删除服务区 "${selectedService.attributes.service_name}" 吗？此操作不可恢复。`
  deleteConfirmVisible.value = true
}

// 执行删除操作
const confirmDelete = () => {
  if (deleteType.value === 'entrance') {
    deleteEntrance()
  } else {
    deleteService()
  }
}

// 删除进出口
const deleteEntrance = () => {
  if (!selectedEntrance || !entranceLayer) return

  entranceLayer
    .applyEdits({
      deleteFeatures: [selectedEntrance],
    })
    .then((result) => {
      if (result.deleteFeatureResults.length > 0) {
        ElMessage.success('进出口删除成功')
        entranceInfoVisible.value = false
        deleteConfirmVisible.value = false
      } else {
        ElMessage.error('进出口删除失败')
      }
    })
    .catch((error) => {
      console.error('删除进出口出错:', error)
      ElMessage.error('进出口删除失败')
    })
}

// 删除服务区
const deleteService = () => {
  if (!selectedService || !serviceLayer) return

  serviceLayer
    .applyEdits({
      deleteFeatures: [selectedService],
    })
    .then((result) => {
      if (result.deleteFeatureResults.length > 0) {
        ElMessage.success('服务区删除成功')
        serviceInfoVisible.value = false
        deleteConfirmVisible.value = false
      } else {
        ElMessage.error('服务区删除失败')
      }
    })
    .catch((error) => {
      console.error('删除服务区出错:', error)
      ElMessage.error('服务区删除失败')
    })
}

// 初始化地图
const initMap = () => {
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    center: [116.397428, 39.90923], // 默认中心点（北京）
    zoom: 8,
  })

  // 创建图形图层用于绘制
  sketchLayer = new GraphicsLayer()
  map.add(sketchLayer)

  // 创建高速公路图层
  highwayLayer = new FeatureLayer({
    url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayManagemnetSystem/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: true,
    popupTemplate: {
      title: '{highway_name}'
    }
  })
  map.add(highwayLayer)

  // 创建进出口图层
  entranceLayer = new FeatureLayer({
    url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayService/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
  })
  map.add(entranceLayer)

  // 创建服务区图层
  serviceLayer = new FeatureLayer({
    url: 'https://services.arcgis.com/pPin4rPIRy9xhFS0/arcgis/rest/services/HighwayService/FeatureServer/1',
    outFields: ['*'],
    popupEnabled: false,
  })
  map.add(serviceLayer)

  // 创建绘图工具
  sketchViewModel = new SketchViewModel({
    view: view,
    layer: sketchLayer,
    pointSymbol: new SimpleMarkerSymbol({
      style: 'circle',
      color: [255, 0, 0, 0.5],
      size: 12,
      outline: {
        color: [255, 0, 0],
        width: 1,
      },
    }),
  })

  // 监听绘图完成事件
  sketchViewModel.on('create', (event) => {
    if (event.state === 'complete') {
      tempGraphic = event.graphic

      // 根据当前模式打开对应的表单
      if (isDrawing.value) {
        formMode.value = 'add'

        // 根据当前操作类型打开对应的表单
        if (isDrawing.value) {
          if (isPoint.value) {
            entranceFormVisible.value = true
          } else {
            serviceFormVisible.value = true
          }
        }

        isDrawing.value = false
      }
    }
  })

  // 监听点击事件，用于选择要素
  view.on('click', async (event) => {
    // 如果正在绘制，不处理点击事件
    if (isDrawing.value) return

    // 转换空间参考
    const mapPoint = event.mapPoint
    // 创建查询对象
    const query = new Query()
    query.geometry = mapPoint
    query.distance = 100 // 点击容差(米)
    query.units = 'meters'
    query.spatialRelationship = 'intersects'
    query.returnGeometry = true
    query.outFields = ['*']

    try {
      // 查询进出口图层
      if (entranceLayer && entranceLayer.visible) {
        const entranceResult = await entranceLayer.queryFeatures(query)
        if (entranceResult.features.length > 0) {
          // 找到进出口，显示信息
          selectedEntrance = entranceResult.features[0]
          entranceInfoVisible.value = true
          refreshEntranceKey.value += 1
          return
        }
      }

      // 查询服务区图层
      if (serviceLayer && serviceLayer.visible) {
        const serviceResult = await serviceLayer.queryFeatures(query)
        if (serviceResult.features.length > 0) {
          // 找到服务区，显示信息
          selectedService = serviceResult.features[0]
          serviceInfoVisible.value = true
          refreshServiceKey.value += 1
          return
        }
      }

      // 如果没有点击到任何要素，显示提示
      ElMessage.info('未选中任何要素')
    } catch (error) {
      console.error('查询要素出错:', error)
      ElMessage.error('查询要素失败')
    }
  })

  // 加载高速公路列表
  loadHighwayList()
}

// 组件挂载时初始化地图
onMounted(() => {
  nextTick(() => {
    initMap()
  })
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (view) {
    view = null
  }
})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.layer-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.layer-card {
  width: 250px;
  background-color: rgba(255, 255, 255, 0.9);
}
</style>
